﻿using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using cfg;
using FrameCore.LogSystem;
using MemoryPack;
using Newtonsoft.Json.Linq;
using Server.Business.Player;
using Share.Memory;

namespace Server.Business.Login
{
    public static class Login
    {
        private static string wx_appId = "wx5449d59832a509bc";
        private static string wx_appSecret = "20b075bdbef22384b30568a0178069e2";
        public static LoginResp GetLoginResp(LoginReq req, out LoginResp resp, out ECode code)
        {
            code = ECode.Success;

            resp = new LoginResp()
            { 
                Uid = req.Name == "mxs" ? 888888 : 999999,
            };

            return resp;
        }
        public static WxLoginResp GetWxLoginResp(WxLoginReq req, out WxLoginResp resp, out ECode code)
        {
            code = ECode.Success;
            // 获取openid
            var openId = GetOpenId(req.Code).Result;
            resp = new WxLoginResp()
            {
                Uid = CreateUid(openId)
            };
            return resp;
        }
        static async Task<string> GetOpenId(string code)
        {
            using (HttpClient client = new HttpClient())
            {
                string url = $"https://api.weixin.qq.com/sns/jscode2session?appid={Tables.Self.WxMiniGameData.GetOrDefault("appId")?.StringValue}&secret={Tables.Self.WxMiniGameData.GetOrDefault("appSecret")?.StringValue}&js_code={code}&grant_type=authorization_code";

                HttpResponseMessage response = await client.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    JObject jsonObj = JObject.Parse(responseBody);
                    string openid = jsonObj["openid"].ToString();
                    Log.Info($"openid获取==={openid}");
                    return openid;
                }
                else
                {
                    Log.Error($"请求失败，状态码: {response.StatusCode}");
                    return null;
                }
            }
        }

        static long CreateUid(string _openid)
        {
            return 0;
        }
    }
}
